package rules

import (
	"ddl_checker/internal/config"
	"ddl_checker/internal/parser"
	"fmt"
	"strings"
)

// SyntaxValidator 语法检查器 - 使用HybridAnalyzer进行语法验证
type SyntaxValidator struct {
	*BaseAPIChecker
}

// NewSyntaxValidator 创建语法检查器
func NewSyntaxValidator() *SyntaxValidator {
	config := APICheckerConfig{
		Enabled:  config.GetBool("SYNTAX_VALIDATOR_ENABLED", false),
		Timeout:  10,
		Endpoint: "",
		ApiKey:   "",
	}
	return &SyntaxValidator{
		BaseAPIChecker: NewBaseAPIChecker("语法检查器", config),
	}
}

// NewSyntaxValidatorEnabled 创建带启用状态的语法检查器
func NewSyntaxValidatorEnabled(enabled bool) *SyntaxValidator {
	config := APICheckerConfig{
		Enabled:  enabled,
		Timeout:  10,
		Endpoint: "",
		ApiKey:   "",
	}
	return &SyntaxValidator{
		BaseAPIChecker: NewBaseAPIChecker("语法检查器", config),
	}
}

// NewSyntaxValidatorWithConfig 创建带配置的语法检查器
func NewSyntaxValidatorWithConfig(config ValidatorConfig) *SyntaxValidator {
	checkerConfig := APICheckerConfig{
		Enabled: config.Enabled,
		Timeout: 10,
	}

	// 从设置中读取超时时间
	if timeout, ok := config.Settings["timeout"].(float64); ok {
		checkerConfig.Timeout = int(timeout)
	}

	return &SyntaxValidator{
		BaseAPIChecker: NewBaseAPICheckerWithSettings("语法检查器", checkerConfig, config.Settings),
	}
}

// Validate 执行语法检查
func (v *SyntaxValidator) Validate(data DDLCheckData) APIResult {
	result := APIResult{
		Details: []string{"### 语法检查"},
	}

	if strings.TrimSpace(data.Script) == "" {
		result.Conclusion = APIConclusionFail
		result.Details = append(result.Details, "❌ 未提供DDL脚本")
		return result
	}

	// 使用HybridAnalyzer进行语法验证
	hybridAnalyzer := parser.NewHybridAnalyzer()
	statements, err := hybridAnalyzer.ParseBatchDDL(data.Script, ";")

	if err != nil {
		result.Conclusion = APIConclusionFail
		result.Details = append(result.Details, fmt.Sprintf("❌ 语法解析失败: %v", err))
		return result
	}

	if len(statements) == 0 {
		result.Conclusion = APIConclusionFail
		result.Details = append(result.Details, "❌ 未找到有效的SQL语句")
		return result
	}

	// 检查每条语句的语法正确性
	errorCount := 0
	for i, stmt := range statements {
		if !stmt.IsValid {
			errorCount++
			result.Details = append(result.Details, fmt.Sprintf("❌ 语句%d语法错误: %s", i+1, stmt.Error))
		}
	}

	if errorCount > 0 {
		result.Conclusion = APIConclusionFail
		result.Details = append(result.Details, fmt.Sprintf("❌ 共发现%d个语法错误", errorCount))
	} else {
		result.Conclusion = APIConclusionPass
		result.Details = append(result.Details, fmt.Sprintf("✅ 语法检查通过，共解析出%d条有效语句", len(statements)))
	}

	return result
}
